<template>
  <div>
    <div v-show="!empty" ref="chartContainer" :style="{ width: '100%', height: computedHeight }" />
    <px-empty v-if="empty" description="暂无数据" />
  </div>
</template>

<script lang="ts" setup>
import * as echarts from "echarts";
import { ref, watch, computed, onMounted, type Ref } from "vue";

import { useEchartsResize } from "@/hooks/useEchartsResize";
import type { ResponseDataOfHealth } from "@/api/erc/spareParts/signboard";

import type { HeightType, PropsTypeForHealthAndType, EmitsTypeForHealthAndType } from "../type";

const props = defineProps<PropsTypeForHealthAndType<ResponseDataOfHealth>>();
const emits = defineEmits<EmitsTypeForHealthAndType>();

const empty = ref(false);
const chartContainer: Ref<HTMLElement | null> = ref(null);
const chartInstance: Ref<echarts.ECharts | null> = ref(null);

const options: echarts.EChartsOption = {
  tooltip: {
    trigger: "item"
  },
  legend: {
    top: "5%",
    left: "center"
  },
  series: [
    {
      name: "",
      type: "pie",
      startAngle: 0,
      endAngle: 360,
      radius: "50%",
      itemStyle: {
        borderRadius: 10,
        borderColor: "#fff",
        borderWidth: 2
      },
      center: ["50%", "60%"],
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: "rgba(0, 0, 0, 0.5)"
        }
      },
      color: ["#4786FF  ", "#14C7C7 ", "#FFB266 ", "#8B8AE6 "]
    }
  ]
};

useEchartsResize(chartInstance, chartContainer, options);

const computedHeight = computed<HeightType>(() => {
  if (props.showTop5Data) {
    return "300px";
  }
  return "600px";
});

const isEmpty = () => {
  let flag = true;
  if (props?.data?.length) {
    props?.data.forEach(item => {
      if (item.value > 0) {
        flag = false;
      }
    });
  }

  return flag;
};

const renderChart = (): void => {
  if (!isEmpty()) {
    empty.value = false;
    chartInstance.value.setOption({
      series: [
        {
          data: props?.data
        }
      ]
    });
  } else {
    empty.value = true;
    emits("resetCode");
  }
};

const initEventListener = () => {
  chartInstance.value.on("click", function (params) {
    const code = (params?.data as any).code;
    emits("pushCode", code);
    emits("getData", props.showTop5Data);
  });
};

watch(
  () => props.data,
  () => {
    renderChart();
  },
  {
    deep: true
  }
);

onMounted(() => {
  renderChart();
  initEventListener();
});
</script>
